<?php

namespace backend\controllers;

use Yii;
use backend\models\Project;
use backend\models\Api;
use backend\models\ModifyLogs;
use yii\base\Exception;
use yii\base\InvalidConfigException;
use yii\web\Response;
use yii\web\request;
use yii\web\NotFoundHttpException;
use yii\filters\AccessControl;
use yii\data\ActiveDataProvider;
use yii\data\Sort;
use backend\components\BackendController;
use yii\widgets\ActiveForm;

class ApiController extends BackendController
{
//    public $layout=false;
    public function beforeAction($action)
    {
        if (Yii::$app->user->isGuest) {
            return $this->redirect(['site/login']);
        } else {
            return true;
        }
        if (!parent::beforeAction($action)) {
            return false;
        }
    }

    /**
     * 首页
     */
    public function actionIndex()
    {
        $data = Project::find()->where('projectId > 0')->orderBy("projectId desc")->all();
        return $this->render('index', [
            'data' => $data,
        ]);
    }

    /**
     * 添加项目
     */
    public function actionAddProject()
    {
        $model = new Project();
        if (Yii::$app->request->isAjax) {
            Yii::$app->response->format = Response::FORMAT_JSON;
            return ActiveForm::validate($model);
        }
        if ($model->load(Yii::$app->request->post()) && $model->save()) {
            // Yii::$app->session->setFlash('success', '您已成功添加项目：'.$model->projectName);
            return $this->redirect(['index']);
        }
        $data = Project::find()->where('projectId > 0')->orderBy("projectId desc")->all();
        return $this->render('addProject', [
            'model' => $model,
            'data' => $data,
            'isEdit' => 0,
        ]);

    }

    /**
     * 编辑项目
     */
    public function actionEditProject()
    {
        $projectId = Yii::$app->request->get('projectId');
        if(!$projectId){ //编辑
            $this->error('参数错误');
        }
        $model = Project::find()->where(['projectId'=>$projectId])->one();
        if(empty($model)){
            $this->error('找不到数据');
        }
        if ($model->load(Yii::$app->request->post()) && $model->save()) {
            return $this->redirect(['index']);
        }
        $data = Project::find()->where('projectId > 0')->orderBy("projectId desc")->all();
        return $this->render('addProject', [
            'model' => $model,
            'data' => $data,
            'isEdit' => 1,
        ]);

    }

    /**
     * 删除项目
     */
    public function actionDeleteProject()
    {
        $projectId = $this->noempty(Yii::$app->request->post('projectId'));
        $tr = Yii::$app->db->beginTransaction();
        try{
            Api::deleteAll(['fkProjectId'=>$projectId]);
            Project::findModel($projectId)->delete();
            $tr->commit();
            return $this->goHome();
        }catch (Exception $e){
            $tr->rollBack();
            return $this->showFlash('删除失败','error',Yii::$app->homeUrl);
        }
    }


    /**
     * 接口信息
     */
    public function actionApiInfo()
    {
        $get = Yii::$app->request->get();
        if (!isset($get['id'])) {
            throw new \yii\web\UnauthorizedHttpException('Missing Params!');
            return false;
        }
        $model = new Api();
        if (!empty($get['apiId'])) {
            $apiId = $get['apiId'];
            $model = $model::find()->with('project')->where('apiId=' . $apiId)->one();
        } else $model = $model::find()->with('project')->where('fkProjectId=' . $get['id'])->one();
        $data = Api::find()->where('fkProjectId=' . $get['id'])->orderBy(['sort' => SORT_DESC])->all();
        $projectName = Project::findOne($get['id'])->projectName;
        $url = '';
        if (count($data) == 0) return $this->redirect(['add-api', 'id' => $get['id'], 'apiId' => $get['apiId']]);
        $logs = new ModifyLogs();
        $logsData = $logs::find()->where('apiId=' . $model->apiId)->orderBy('editTime desc')->all();
        return $this->render('apiInfo', [
            'model' => $model,
            'data' => $data,
            'projectName' => $projectName,
            'logsData' => $logsData,
        ]);
    }
	
	
	public function actionSort()
	{
        $get = Yii::$app->request->get();
        $post = Yii::$app->request->post();
	    //提交排序
		if (Yii::$app->request->isPost) {
		    $ord = count($post['api']);
			$fkid=$post['id'];
			
			$sql="";
            foreach($post['api'] as $v){
                 //
                 $sql.="UPDATE api SET sort={$ord} WHERE apiId={$v};";
				 $ord--;
            }

			Yii::$app->db->createCommand($sql)->execute();
				
			$model = new Api();
            $project = new Project();
			
			
            $data = $model::find()->where('fkProjectId=' . $fkid)->orderBy(['sort' => SORT_DESC])->all();
            $projectName = Project::findOne($fkid)->projectName;
            
			return $this->redirect(['sort', 'id' => $fkid]);
		}
	
	    //展示数据
	    if (!isset($get['id'])) {
            throw new \yii\web\UnauthorizedHttpException('Missing Params!');
            return false;
        }else{
		    $model = new Api();
            $project = new Project();
			
			
            $data = $model::find()->where('fkProjectId=' . $get['id'])->orderBy(['sort' => SORT_DESC])->all();
			
			
            $projectName = Project::findOne($get['id'])->projectName;
            
            return $this->render('sortApi', [
                'data' => $data,
                'projectName' => $projectName,
            ]);
        } 
	
	}


    /**
     * 添加接口
     */
    public function actionAddApi()
    {
        $get = Yii::$app->request->get();
        $post = Yii::$app->request->post();
        $model = new Api();
        //保存修改
        if (Yii::$app->request->isPost) {
            // api接口数据，如果存在此apiId则修改，否则添加
            $now = date('Y-m-d H:i:s', time());
            if ($post['apiId'] > 0) $model = Api::findOne($post['apiId']);
            $model->load(Yii::$app->request->post());
            $model->userId = Yii::$app->user->identity->id;
            $model->fkProjectId = $post['id'];
            $model->lastTime = $now;
            if (isset($post['p'])) $model->params = serialize($post['p']);
            if (isset($post['r'])) $model->returnParams = serialize($post['r']);
            if (isset($post['returnResult'])) $model->returnResult = $post['returnResult'];
            if (isset($post['remark'])) $model->remark = $post['remark'];
            // 事务开始
            $transaction = Yii::$app->db->beginTransaction();
            $flag1 = $model->save();
            // log数据
            $logs = new ModifyLogs();
            $logs->content = $post['log'];
            $logs->editTime = $now;
            $logs->apiId = $model->apiId;
            $logs->userId = Yii::$app->user->identity->id;

            $flag2 = $logs->save();
            Yii::$app->session->setFlash('success', '您已成功编辑接口：' . $model->apiName);
            //二者都成功则提交，否则回滚
            if ($flag1 && $flag2) {
                $transaction->commit();
                return $this->redirect(['api-info', 'id' => $model->fkProjectId, 'apiId' => $model->apiId]);
            } else {
                $transaction->rollBack();
                throw new \yii\web\UnauthorizedHttpException('Missing Params!');
            }
        }
        //展示添加或编辑页面
        if (isset($get['id']) && isset($get['apiId'])) {
            $project = new Project();
            $data = $model::find()->where('fkProjectId=' . $get['id'])->all();
            $projectName = Project::findOne($get['id'])->projectName;
            $apiId = $get['apiId'];
            if ($apiId > 0) $model = $model::find()->with('project')->orderBy(['sort' => SORT_DESC])->where('apiId=' . $apiId)->one();
            return $this->render('addApi', [
                'model' => $model,
                'data' => $data,
                'projectName' => $projectName,
            ]);
        } else {
            throw new \yii\web\UnauthorizedHttpException('Missing Params!');
        }
    }

    /**
     * 复制接口
     */
    public function actionCopy()
    {
        $get = Yii::$app->request->get();
        if (isset($get['apiId']) && isset($get['name'])) {
            $model = new Api();
            $now = date('Y-m-d H:i:s', time());
            if ($get['apiId'] > 0) $model = Api::findOne($get['apiId']);
            //$model->load(Yii::$app->request->post());

            $apiId = $get['apiId'];

            $model->apiId = NULL;
            $projectid = $model->fkProjectId;
            $max = Yii::$app->db->createCommand("select max(Number) as maxNum from api where fkProjectId='$projectid'")->queryScalar();

            $maxNum = (string)($max + 1);

            $model->number = $maxNum;
            $model->userId = Yii::$app->user->identity->id;
            $model->lastTime = $now;
            $model->apiName = $get['name'];


            $newmodel = new Api();
            $newmodel->fkProjectId = $model->fkProjectId;
            $newmodel->functionName = $model->functionName;
			$newmodel->apiUrl = $model->apiUrl;
            $newmodel->apiName = $model->apiName;
            $newmodel->number = $model->number;
            $newmodel->params = $model->params;
			$newmodel->returnResult = $model->returnResult;
            $newmodel->type = $model->type;
            $newmodel->lastTime = $model->lastTime;
            $newmodel->apiDiscribe = $model->apiDiscribe;
            $newmodel->returnParams = $model->returnParams;
            $newmodel->userId = $model->userId;
            $newmodel->lastTime = $model->lastTime;
			$newmodel->remark = $model->remark;


            // 事务开始
            $transaction = Yii::$app->db->beginTransaction();
            $flag1 = $newmodel->save();

            //成功则提交，否则回滚
            if ($flag1) {
                $transaction->commit();
                return $this->redirect(['api-info', 'id' => $newmodel->fkProjectId, 'apiId' => $newmodel->apiId]);
            } else {
                $transaction->rollBack();
                throw new \yii\web\UnauthorizedHttpException('Missing Params!');
            }


        }else{
		    $this->error('参数错误');
		}

    }

    /**
     * 删除接口
     */
    public function actionDel()
    {
        $post = Yii::$app->request->post();
        $status = '{"code":-1}';
        if (Yii::$app->request->isAjax && isset($post['apiId'])) {
            $model = new Api();
            $model = Api::deleteAll('apiId=' . $post['apiId']);
            if ($model) $status = '{"code":0}';
        }
        echo $status;
    }

    

    /**
     * 搜索接口/工程
     * @param type:1 -->搜索接口，2-->搜索工程
     */
    public function actionSearch()
    {
        $post = Yii::$app->request->post();
        $data = array();
        if ($post['type'] == 1) {
            $model = new Api();
            $data = $model::find()->where("number like '%" . $post['keywords'] . "%' or apiName like '%" . $post['keywords'] . "%'")->all();
        } else if ($post['type'] == 2) {
            $model = new Project();
            $data = $model::find()->where("projectName like '%" . $post['keywords'] . "%'")->all();
        }
        return \yii\helpers\Json::encode($data);
    }






































































}
